package mr.zhang.service.impl;

import mr.zhang.service.WeChatService;
import mr.zhang.weixin.message.resp.Article;
import mr.zhang.weixin.message.resp.NewsMessage;
import mr.zhang.weixin.message.resp.TextMessage;
import mr.zhang.weixin.wechatutil.MessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by jerry on 15/1/22.
 * E-mail:huaxinxc@me.com
 */
public class WeChatServiceImpl implements WeChatService{


    private String buttonDao;
    private String subButtonDao;


    public void setButtonDao(String buttonDao) {
        this.buttonDao = buttonDao;
    }

    public void setSubButtonDao(String subButtonDao) {
        this.subButtonDao = subButtonDao;
    }

    private static Logger log = LoggerFactory.getLogger(WeChatServiceImpl.class);

    /**
     * 微信接口菜单设置
     *
     * @param obj
     */
    @Override
    public void setWeChatMenu(Object obj) {

    }

    /**
     * 更新微信接口
     *
     * @param obj
     */
    @Override
    public void updataWeChatMenu(Object obj) {

    }

    /**
     * 删除按钮
     *
     * @param id
     */
    @Override
    public void deleteWeChatMenu(Integer id) {

    }

    /**
     * 添加按钮
     *
     * @param object
     */
    @Override
    public void createWeChatButton(Object object) {

    }

    /**
     * 弹出消息推送 @see Article
     * title 标题
     * url 跳转地址
     * description  简介
     * picUrl   图片路径
     *
     * @param article
     */
    @Override
    public void pushNewsByWeChat(Article article) {

    }

    /**
     * 删除推送消息
     *
     * @param id
     */
    @Override
    public void deleteNewsByWeChat(Integer id) {

    }

    /**
     * 更新 推送消息 @see Article
     * title       标题
     * url         跳转地址
     * description 简介
     * picUrl      图片路径
     *
     * @param article
     */
    @Override
    public void updataNewsByWeChat(Article article) {

    }

    /**
     * 设置 View 类型的Button 跳转地址 （待定）
     *
     * @param url
     */
    @Override
    public void setViewButton(String url) {

    }

    /**
     * 取得所有关注者的openID
     *
     * @param accessToken
     * @return
     */
    @Override
    public List<Object> getWeChatFansList(String accessToken) {
        return null;
    }

    /**
     * 处理来自微信服务器的请求（核心）
     *
     * @param request
     * @return
     */
    @Override
    public String processRequest(HttpServletRequest request) {
        String respMessage = null;
        String path = request.getRequestURI().substring(0);


        try {
            // 默认返回的文本消息内容
            String respContent = "请求处理异常，请稍候尝试！";

            // xml请求解析
            Map<String, String> requestMap = MessageUtil.parseXml(request);


            // 发送方帐号（open_id）
            String fromUserName = requestMap.get("FromUserName");
            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");


            // 接收用户发送的文本消息内容
            String content = requestMap.get("Content");

            // 创建图文消息
            NewsMessage newsMessage = new NewsMessage();
            newsMessage.setToUserName(fromUserName);
            newsMessage.setFromUserName(toUserName);
            newsMessage.setCreateTime(new Date().getTime());
            newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
            newsMessage.setFuncFlag(0);

            List<Article> articleList = new ArrayList<Article>();

            respMessage = MessageUtil.newsMessageToXml(newsMessage);



            log.info("formusername,tousernam msatype",fromUserName + toUserName +msgType);

            // 回复文本消息
            TextMessage textMessage = new TextMessage();
            textMessage.setToUserName(fromUserName);
            textMessage.setFromUserName(toUserName);
            textMessage.setCreateTime(new Date().getTime());
            textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
            textMessage.setFuncFlag(0);

            // 文本消息
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {

                if(msgType == "首页"){
                    respContent ="你敢跳转首页 ，那么你来对了";
                }else {
                    respContent = "您发送的是文本消息！";
                }
            }
            // 图片消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
                respContent = "您发送的是图片消息！";
            }
            // 地理位置消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
                respContent = "您发送的是地理位置消息！";
            }
            // 链接消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
                respContent = "您发送的是链接消息！";
            }
            // 音频消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
                respContent = "您发送的是音频消息！";
            }
            // 事件推送
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
                // 事件类型
                String eventType = requestMap.get("Event");
                // 订阅
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                    respContent = "谢谢您的关注！";
                }
                // 取消订阅
                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
                    // TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
                }
                // 自定义菜单点击事件
                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
                    // 事件KEY值，与创建自定义菜单时指定的KEY值对应
                    String eventKey = requestMap.get("EventKey");

                    if (eventKey.equals("11")) {
                        respContent = "天气预报被点击";
                    } else if (eventKey.equals("12")) {
                        //respContent = "12被点击！";
                        System.out.println("创建图文信息 article");
                        // 将文本消息对象转换成xml字符串


                        Article article1 = new Article();
                        article1.setTitle("创建图文信息\n引言");
                        article1.setDescription("test test test  简介");
                        article1
                                .setPicUrl("http://www.sddianfeng.com/UploadFiles/20140927174436557.jpg");
                        article1
                                .setUrl("http://baidu.com");

                        Article article2 = new Article();
                        article2.setTitle("创建图文信息2");
                        article2.setDescription("test test test  简介");
                        article2
                                .setPicUrl("http://www.sddianfeng.com/UploadFiles/20140927174436557.jpg");
                        article2
                                .setUrl("http://mp.weixin.qq.com");

                        articleList.add(article1);
                        articleList.add(article2);

                        newsMessage.setArticleCount(articleList.size());
                        newsMessage.setArticles(articleList);
                        respMessage = MessageUtil.newsMessageToXml(newsMessage);
                        System.out.println("淡出菜单中显示 穿地值" + respMessage);
                        return  respMessage;


                    } else if (eventKey.equals("13")) {
                        respContent = "13被点击！";
                    } else if (eventKey.equals("14")) {
                        respContent = "历史上的今天菜单项被点击！";
                    } else if (eventKey.equals("21")) {
                        respContent = "西昌新闻被点击！";
                    } else if (eventKey.equals("22")) {
                        respContent = "促销！";
                    } else if (eventKey.equals("23")) {
                        respContent = "优惠！";
                    } else if (eventKey.equals("24")) {
                        respContent = "抢bank";
                    } else if (eventKey.equals("25")) {
                        respContent = "同城聊天！";
                    } else if (eventKey.equals("31")) {

                        respContent = "31被点击！" + path;

                    } else if (eventKey.equals("32")) {
                        respContent = "商家合作被点击！";
                    } else if (eventKey.equals("33")) {
                        respContent = "投诉建议！"+path;
                    }
                }
            }



            textMessage.setContent(respContent);
            respMessage = MessageUtil.textMessageToXml(textMessage);


        } catch (Exception e) {
            e.printStackTrace();
        }

        log.info("reqMessage" + respMessage.toString());

        return respMessage;
    }
}
